package logic

import (
	"MyBlogv2/Servers/WebSiteInfo/internal/svc"
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/define"
	"MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"

	"MyBlogv2/Servers/WebSiteInfo/webSiteInfo"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetWebsiteInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetWebsiteInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWebsiteInfoLogic {
	return &GetWebsiteInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetWebsiteInfoLogic) GetWebsiteInfo(in *webSiteInfo.WebSiteInfoRequest) (*webSiteInfo.GetWebsiteInfoResponse, error) {
	var websiteInfoVo models.WebsiteInfoVo
	var lastUpdateTime models.MyTime
	var articleCount int64
	var wordCount int
	var visitCount int
	var categoryCount int64
	var commentCount int64
	var allArticleContent []string
	models.Db.Model(new(models.WebsiteInfo)).First(&websiteInfoVo)
	models.Db.Model(new(models.Article)).Select("updated_at").Order("updated_at desc").First(&lastUpdateTime)
	models.Db.Model(new(models.Article)).Where("status = ?", define.PUBLIC_ARTICLE).Count(&articleCount)
	models.Db.Model(new(models.Article)).Select("article_content").Find(&allArticleContent)
	for i := 0; i < len(allArticleContent); i++ {
		wordCount += len(allArticleContent[i])
	}
	models.Db.Model(new(models.Article)).Select("sum(visit_count)").Scan(&visitCount)
	models.Db.Model(new(models.Category)).Count(&categoryCount)
	models.Db.Model(new(models.Comment)).Count(&commentCount)
	websiteInfoVo.WordCount = wordCount
	websiteInfoVo.LastUpdateTime = lastUpdateTime
	websiteInfoVo.ArticleCount = int(articleCount)
	websiteInfoVo.VisitCount = visitCount
	websiteInfoVo.CategoryCount = int(categoryCount)
	websiteInfoVo.CommentCount = int(commentCount)

	var websiteInfoVoResponse webSiteInfo.WebsiteInfoVo
	copier.Copy(&websiteInfoVoResponse, &websiteInfoVo)
	websiteInfoVoResponse.StartTime = helper.MyTimeToTimestamp(websiteInfoVo.StartTime)
	websiteInfoVoResponse.LastUpdateTime = helper.MyTimeToTimestamp(websiteInfoVo.LastUpdateTime)

	return &webSiteInfo.GetWebsiteInfoResponse{
		Code: int64(HttpCode.SUCCESS),
		Data: &websiteInfoVoResponse,
	}, nil
}
